package com.lap.framework.generator.shared.enums;

import java.util.IllegalFormatConversionException;
import java.util.MissingFormatArgumentException;
import java.util.Objects;
import lombok.Getter;

@Getter
public enum AnnotationType {

  /** 通用SWAGGER属性注解 */
  SCHEMA("@Schema(description = \"%s\", type = \"%s\", example = \"%s\")"),

  /** 一般字符串,不为null,trim()!="" */
  NOT_BLANK("@NotBlank(message = \"{%s}\")"),

  /** 所有类型,不为null */
  NOT_NULL("@NotNull(message = \"{%s}\")"),

  /** 长度,字符串长度不超过 */
  LENGTH("@Length(max = %s, message = \"{%s}\")"),

  /** 元素必须是一个数字，其值必须大于等于指定的最小值 */
  NUMBER_MIN("@Min(value = %s, message = \"{%s}\")"),

  /** 元素必须是一个数字，其值必须小于等于指定的最大值 */
  NUMBER_MAX("@Max(value = %s, message = \"{%s}\")"),

  /** 元素区间值 */
  NUMBER_RANGE("@Range(min = %s, max = %s, message = \"{%s}\")"),
  ;

  private final String value;

  AnnotationType(String value) {
    this.value = value;
  }

  public static String getAnnotation(AnnotationType type, Object... objs) {
    Objects.requireNonNull(type, "AnnotationType cannot be null");

    try {
      return String.format(type.value, objs);
    } catch (MissingFormatArgumentException e) {
      throw new IllegalArgumentException(
          String.format(
              "Missing arguments for %s. Expected %d parameters but got %d",
              type.name(), countFormatSpecifiers(type.value), objs.length),
          e);
    } catch (IllegalFormatConversionException e) {
      throw new IllegalArgumentException(
          String.format("Invalid argument type for %s: %s", type.name(), e.getMessage()), e);
    }
  }

  private static int countFormatSpecifiers(String format) {
    int count = 0;
    for (int i = 0; i < format.length(); i++) {
      if (format.charAt(i) == '%' && i + 1 < format.length()) {
        if (format.charAt(i + 1) == 's') {
          count++;
        }
        i++; // 跳过格式说明符
      }
    }
    return count;
  }
}
